package com.fsd.core.activiti;

import org.activiti.engine.*;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import java.util.List;

/**
 * ================================
 * @Description: Activiti 工具类
 * @Author: lumingbao
 * @Date 2018-12-06 11:10
 * ================================
 */
public class ActivitiUtil {

    private static ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    private static RepositoryService repositoryService = processEngine.getRepositoryService();

    private static RuntimeService runtimeService = processEngine.getRuntimeService();

    private static TaskService taskService = processEngine.getTaskService();

    private static FormService formService = processEngine.getFormService();

    private static HistoryService historyService = processEngine.getHistoryService();

    /**
     * 任务类型 - 用户任务
     */
    public static final String TASK_TYPE_USERTASK = "userTask";
    /**
     * 任务类型 - 排他网关
     */
    public static final String TASK_TYPE_EXCLUSIVEGATEWAY = "exclusiveGateway";

    /**
     * 获得用户的任务列表
     * @param userid
     * @return
     * @throws Exception
     */
    public static List<Task> getTaskList(String userid) throws Exception{
        List<Task> list = taskService.createTaskQuery().taskAssignee(userid).orderByTaskCreateTime().asc().list();
        if(null == list || list.size() < 1){
            // 如果指定个人任务为空，则查询多人任务
            list = taskService.createTaskQuery().taskCandidateUser(userid).orderByTaskCreateTime().asc().list();
        }
        if(null == list || list.size() < 1){
            // 如果指定多人任务为空在获取组的任务
            list = taskService.createTaskQuery().taskCandidateGroup(userid).orderByTaskCreateTime().asc().list();
        }
        return list;
    }

    /**
     * 获得下一个任务任务节点的类型
     * @param taskId
     * @return
     * @throws Exception
     */
    public static String getNextTaskType(String taskId) throws Exception{
        String type = "";
        ProcessDefinitionEntity processDefinitionEntity = null;
        String id = null;
        TaskDefinition task = null;
        //获取流程实例Id信息
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        //获取流程发布Id信息
        String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();
        processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(definitionId);
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //当前流程节点Id信息
        String activitiId = execution.getActivityId();
        //获取流程所有节点信息
        List<ActivityImpl> activitiList = processDefinitionEntity.getActivities();
        //遍历所有节点信息
        for(ActivityImpl activityImpl : activitiList){
            id = activityImpl.getId();
            if (activitiId != null && activitiId.equals(id)) {
                //获取下一个节点信息
                String activityId = activityImpl.getId();
                String elString = null;

                PvmActivity ac = null;
                Object s = null;
                // 如果遍历节点为用户任务并且节点不是当前节点信息
                if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
                    type = "userTask";
                    return type;
                } else {
                    // 获取节点所有流向线路信息
                    List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
                    List<PvmTransition> outTransitionsTemp = null;
                    for (PvmTransition tr : outTransitions) {
                        // 获取线路的终点节点
                        ac = tr.getDestination();
                        // 如果流向线路为排他网关
                        if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                            type = "exclusiveGateway";
                            return type;
                        } else if ("userTask".equals(ac.getProperty("type"))) {
                            type = "userTask";
                            return type;
                        } else {

                        }
                    }
                    return null;
                }
            }
        }
        return type;
    }

    /**
     * 获取下一个用户任务
     * @param taskId
     * @return
     * @throws Exception
     */
    public static TaskDefinition getNextTaskInfo(String taskId, String elString) throws Exception {
        ProcessDefinitionEntity processDefinitionEntity = null;
        String id = null;
        TaskDefinition task = null;
        //获取流程实例Id信息
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        //获取流程发布Id信息
        String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();
        processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(definitionId);
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //当前流程节点Id信息
        String activitiId = execution.getActivityId();
        //获取流程所有节点信息
        List<ActivityImpl> activitiList = processDefinitionEntity.getActivities();
        //遍历所有节点信息
        for(ActivityImpl activityImpl : activitiList){
            id = activityImpl.getId();
            if (activitiId.equals(id)) {
                //获取下一个节点信息
                task = nextTaskDefinition(activityImpl, activityImpl.getId(), elString, processInstanceId);
                break;
            }
        }
        return task;
    }

    /**
     * 获得下一个网关信息
     * @param taskId
     * @return
     * @throws Exception
     */
    public static List<PvmTransition> getNexGatewayInfo(String taskId) throws Exception{
        List<PvmTransition> outTransitionsTemp = null;
        ProcessDefinitionEntity processDefinitionEntity = null;
        String id = null;
        TaskDefinition task = null;
        //获取流程实例Id信息
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        //获取流程发布Id信息
        String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();
        processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(definitionId);
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //当前流程节点Id信息
        String activitiId = execution.getActivityId();
        //获取流程所有节点信息
        List<ActivityImpl> activitiList = processDefinitionEntity.getActivities();
        //遍历所有节点信息
        for(ActivityImpl activityImpl : activitiList){
            id = activityImpl.getId();
            if (activitiId.equals(id)) {
                //获取下一个节点信息
                String activityId = activityImpl.getId();
                PvmActivity ac = null;
                // 如果遍历节点为用户任务并且节点不是当前节点信息
                if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {

                } else {
                    // 获取节点所有流向线路信息
                    List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
                    for (PvmTransition tr : outTransitions) {
                        // 获取线路的终点节点
                        ac = tr.getDestination();
                        // 如果流向线路为排他网关
                        if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                            outTransitionsTemp = ac.getOutgoingTransitions();
                        }
                    }
                }
            }
        }
        return outTransitionsTemp;
    }

    /**
     * 下一个任务节点信息,
     * 如果下一个节点为用户任务则直接返回,
     * 如果下一个节点为排他网关, 获取排他网关Id信息, 根据排他网关Id信息和execution获取流程实例排他网关Id为key的变量值,
     * 根据变量值分别执行排他网关后线路中的el表达式, 并找到el表达式通过的线路后的用户任务
     * @param activityImpl     流程节点信息
     * @param activityId             当前流程节点Id信息
     * @param elString               排他网关顺序流线段判断条件
     * @param processInstanceId      流程实例Id信息
     * @return
     */
    private static TaskDefinition nextTaskDefinition(ActivityImpl activityImpl, String activityId, String elString, String processInstanceId){
        PvmActivity ac = null;
        Object s = null;
        // 如果遍历节点为用户任务并且节点不是当前节点信息
        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            // 获取该节点下一个节点信息
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior()).getTaskDefinition();
            return taskDefinition;
        } else {
            // 获取节点所有流向线路信息
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;
            for (PvmTransition tr : outTransitions) {
                // 获取线路的终点节点
                ac = tr.getDestination();
                // 如果流向线路为排他网关
                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();
                    // 如果网关路线判断条件为空信息
                    if (StringUtils.isEmpty(elString)) {
                        // 获取流程启动时设置的网关判断条件信息
                        elString = getGatewayCondition(ac.getId(), processInstanceId);
                    }
                    // 如果排他网关只有一条线路信息
                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId,
                                elString, processInstanceId);
                    } else if (outTransitionsTemp.size() > 1) {
                        // 如果排他网关有多条线路信息
                        for (PvmTransition tr1 : outTransitionsTemp) {
                            // 获取排他网关线路判断条件信息
                            s = tr1.getProperty("conditionText");
                            // 判断el表达式是否成立
                            if (elString.equals(StringUtils.trim(s.toString()))) {
                                return nextTaskDefinition((ActivityImpl) tr1.getDestination(), activityId, elString, processInstanceId);
                            }
                        }
                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {
                    return ((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition();
                } else {
                }
            }
            return null;
        }
    }

    /**
     * 查询流程启动时设置排他网关判断条件信息
     * @param gatewayId          排他网关Id信息, 流程启动时设置网关路线判断条件key为网关Id信息
     * @param processInstanceId  流程实例Id信息
     * @return
     */
    public static String getGatewayCondition(String gatewayId, String processInstanceId) {
        Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).singleResult();
        Object object= runtimeService.getVariable(execution.getId(), gatewayId);
        return object==null? "":object.toString();
    }

    /**
     * 根据流程实例ID删除历史流程
     * @param processInstanceId 流程实例ID
     */
    public static void deleteHistoricProcessInstanceById(String processInstanceId) throws Exception{
        historyService.deleteHistoricProcessInstance(processInstanceId);;
    }

    /**
     * 根据流程实例ID删除正在运行的流程
     * @param processInstanceId
     * @throws Exception
     */
    public static void deleteProcessInstanceById(String processInstanceId) throws Exception{
        runtimeService.deleteProcessInstance(processInstanceId, "");
    }

    /**
     * 根据部署ID查看流程图
     * @param deploymentId
     * @return
     * @throws Exception
     */
    public static String getDeploymentResourceUrl(String deploymentId, String resourceName) throws Exception{

        return "";
    }

    /**
     * 根据任务id加载任务信息
     * @param taskid
     * @return
     * @throws Exception
     */
    public static Task getTaskByTaskid(String taskid){
        Task task = taskService.createTaskQuery().taskId(taskid).singleResult();
        return task;
    }
}
